import Vue from 'vue'
import axios from 'axios'
import {
  removeToken,
  API_SUCCESS_CODE,
  getToken
} from '@/utils'

let baseURL = process.env.SURVEY_API;
if (process.env.NODE_ENV === 'development') {
  // baseURL = 'http://39.100.66.128:8082'; // 测试
  // baseURL = 'http://172.16.2.182:9097'; // 测试
  // baseURL = 'http://47.96.232.83:8083'; // 测试
  baseURL = 'https://dev.jyrj360.com/'; // 测试
}



function JTO(str) {
   var reg = /: *\d{14,20} */g
   str = str.replace(reg, function(a) {
     return a.replace(/: */g, ":\"").replace(" ", "") + "\""
   })
   return str
}

// 创建axios实例
const service = axios.create({
  baseURL,
  timeout: 60000, // 请求超时时间
  withCredentials: false,
  // transformResponse 允许自定义原始的响应数据（字符串）
    transformResponse: [function (data) {
      try {
        return JSON.parse(JTO(data))
      } catch (err) {
        // 如果转换失败，则包装为统一数据格式并返回
        return {
          data
        }
      }
    }]
})


// request拦截器
service.interceptors.request.use(config => {
  config.headers.Authorization = 'Bearer eyJhbGciOiJIUzUxMiJ9.eyJ1c2VyX2NhY2hlX2tleSI6InVzZXJfY2FjaGVfa2V5Ond4MjAyMjAzOjE5OTI6NzJmOTQ2MzktYmM3YS00ZmZhLTg4MjUtMDc2NjJkYTdiM2I1IiwibG9naW5fdG9rZW5fa2V5IjoiZjQ4YmExYTUtNmU0NS00MmQ3LWE4YWMtNWJhMzc1YzY5ZDc3In0.bPjSwX54_HqPB-Ih08X7eEvoLSGB0aZJcyDEIRLoFhlWbiXXGAsXtE6rF-a8oFOJbTQDQiOb69ec06O-79H8mQ'
  // config.headers.Authorization = window.appToken
  if (config.showLoading) {
  }



  return config
}, error => {
  console.log(error)
  Promise.reject(error)
})

// response拦截器
service.interceptors.response.use(response => {
  const res = response.data;
  if (res === null) {
    return res
  }
  if (res.code === API_SUCCESS_CODE && !res.data) {
    res.data = 1;
  }
  if (res.code !== API_SUCCESS_CODE) {
    res.data = null;
  }
  // token 过期
  if (res.code === 'A100003') {
    removeToken();
    // window.location.href = window.location.origin + '/#/userlogin';
  } else if (response && response.headers && response.headers['content-type'] && response.headers['content-type'] === 'application/octet-stream;charset=UTF-8') {
    return response;
  } else if (res.code && res.code !== API_SUCCESS_CODE) {
    res.msg && Vue.prototype.$message.error(res.msg);
    return res;
  } else {
    return res;
  }
}, error => {
  console.log(error.response);
  removeToken();
  const res = error.response.data;
  const status = error.response.status;
  if (status === 403) {
    console.log('postMessage');
    window.parent.postMessage({
      type: 'Event',
      name: 'Event_refreshToken',
      data: {
        token: ''
      }
    }, '*')
  } else if (status === 429) {
    Vue.prototype.$message.error('操作频繁，请稍后再试')
    return;
  }
  res.msg && Vue.prototype.$message.error(res.msg);
  Promise.reject(error)
})
export default service
